var data;

var checkForOwnRatings = function(parentDiv) {
	var radioBtns = parentDiv.getElementsByTagName('input'), 
		accessToken = localStorage.getItem('access-token');
	$.ajax({
		type : 'GET',
		url : 'api/rating',
		beforeSend : function(request) {
			request.setRequestHeader('Accept','application/json; charset=utf-8');
			request.setRequestHeader("access-token", accessToken);
		}
	}).fail(function(jgXHR, textStatus) {
		alert(jgXHR.status + ': ' + textStatus);
	}).success(function(data, textStatus, request) {
		for(var k=0; k<data.length; k++) {
			var movieVoted = document.getElementById(data[k].movie.imdbtt),
				radioBoxes = movieVoted.getElementsByTagName('input');
			movieVoted.setAttribute('ratingid', data[k].id);
				
			for(var i=0; i<radioBoxes.length; i++) {
				if(radioBoxes[i].parentNode.getElementsByTagName('div')[0].innerHTML == data[k].stars) {
					radioBoxes[i].checked = true;
				}
			}
		}
	});
};

var makeNewRating = function(imdbtt, value) {
	var accessToken = localStorage.getItem('access-token');
	$.ajax({
		type : 'POST',
		url : 'api/rating',
		beforeSend : function(request) {
			request.setRequestHeader("access-token", accessToken);
			request.setRequestHeader("imdbtt", imdbtt);
			request.setRequestHeader("rating", value);
		}
	}).fail(function(jgXHR, textStatus) {
		alert(jgXHR.status + ': ' + textStatus);
	}).success(function(data, textStatus, request) {
		location.reload();
	});
}

var sendRatingUpdate = function(value, ratingId) {
	var accessToken = localStorage.getItem('access-token');
	$.ajax({
		type : 'PUT',
		url : 'api/rating',
		beforeSend : function(request) {
			request.setRequestHeader("access-token", accessToken);
			request.setRequestHeader("ratingId", ratingId);
			request.setRequestHeader("rating", value);
		}
	}).fail(function(jgXHR, textStatus) {
		alert(jgXHR.status + ': ' + textStatus);
	}).success(function(data, textStatus, request) {
		location.reload();
	});
};

var deleteRating = function(ratingId) {
	var accessToken = localStorage.getItem('access-token');
	$.ajax({
		type : 'DELETE',
		url : 'api/rating/' + ratingId,
		beforeSend : function(request) {
			request.setRequestHeader("access-token", accessToken);
		}
	}).fail(function(jgXHR, textStatus) {
		alert(jgXHR.status + ': ' + textStatus);
	}).success(function(data, textStatus, request) {
		location.reload();
	});
}